
import axios from 'axios'// 准备actions和mutations

export default {
  namespaced: true,
  state: {
    list: []
  },
  mutations: {
    setList (state, list) {
      state.list = list
    },
    // 根据传递过来的id和数量进行修改
    setListCount (state, obj) {
      // 根据Id找到数组中的元素
      const result = state.list.find(item => item.id === obj.id)
      // 修改元素的count属性
      result.count = obj.num
    }
  },
  actions: {
    // 由于数据在服务器上,获取数据是异步操作,所以要在actions中写代码
    async getCarts (context) {
      const res = await axios.get('http://localhost:3000/cart')
      // 子模块内部调用不需要加模块名
      context.commit('setList', res.data)
    },
    async setCount (context, obj) {
      await axios.patch('http://localhost:3000/cart/' + obj.id, {
        count: obj.num
      })
      context.commit('setListCount', obj)
    }
  },
  getters: {}
}
